package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.CollectUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.ems.config.OpsLog;
import com.dctp.ems.interceptor.OpsLogInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.List;
import java.util.stream.Collectors;

@Path("/userAuth")
public class UserAuthController extends BaseController {

    public void list() {
        Long userId = getParaToLong("userId");
        List<String> rows = Db.query("select auth from dctp_user_auth where user_id = ?", userId);
        renderJson(JsonResult.successWithData(rows));
    }


    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "用户管理",
            action = "更新权限",
            table = "dctp_user_auth",
            fields = {"auths"})
    public void save() {
        Long userId = getParaToLong(0);
        Record body = jsonBody();
        String auths = body.getStr("auths");

        List<String> oldAuths = Db.query("select auth from dctp_user_auth where user_id = ?", userId);
        Db.update("delete from dctp_user_auth where user_id = ?", userId);
        if (StringUtil.isNotEmpty(auths)) {
            for (String auth : auths.split(",")) {
                Record r = new Record();
                r.set("auth", auth);
                r.set("user_id", userId);
                Db.save("dctp_user_auth",r);
            }
        }

        Record oldRecord = new Record();
        oldRecord.set("user_id", userId);
        oldRecord.set("auths", CollectUtil.isEmpty(oldAuths) ? "" : String.join(",", oldAuths));
        setAttr("oldRecord",oldRecord);
        renderJson(JsonResult.success());
    }
}
